﻿using System;
using System.Collections;
using System.Collections.Generic;
using Common.DTOS;
using Common.Net;
using JHY.Client.Assets.Scripts.Tools;
using UnityEngine;

public partial class NetManager : MonoSingleTon<NetManager>
{
    private Dictionary<RequestType, Action<MsgInfo>> requestDic =
        new Dictionary<RequestType, Action<MsgInfo>>();

    public void StartService()
    {
        UClient.Instance.Connect();
        UClient.HandlerController += DispatcherMsg;
        RegisterRequest();
    }

    /// <summary>
    /// This function is called every fixed framerate frame, if the MonoBehaviour is enabled.
    /// </summary>
    private void FixedUpdate()
    {
        UClient.Instance.Dispatch();
    }

    private void OnDestroy()
    {
        UClient.HandlerController -= DispatcherMsg;
    }

    private void DispatcherMsg(MsgInfo info)
    {
        if (requestDic.ContainsKey(info.requestType))
        {
            requestDic[info.requestType].Invoke(info);
        }
        else
        {
            Debug.LogError($"No handler for request type: {info.requestType}");
        }
    }

    public void Send(MsgInfo msg)
    {
        UClient.Instance.Send(msg);
    }

    /// <summary>
    /// Update is called every frame, if the MonoBehaviour is enabled.
    /// </summary>
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.C))
        {
            var clogin = new CLoginDto() { account = "test", password = "123" };
            var msg = new MsgInfo() { requestType = RequestType.CLogin, vo = clogin };

            Send(msg);
            Debug.Log("Send CLogin");
        }
    }
}
